/**
 * Created by GadflyBSD on 16/3/18.
 */
var meta = new Object();
var content = document.getElementsByTagName('meta');
var templatePath = '/Public/template/Business/';
var wait=60;
for(var i = 0; i < content.length; i++){
	if(content[i].getAttribute('name') == 'Authcode')
		meta.appurl = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'appurl')
		meta.verifyImg = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'upload')
		meta.upload = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'angular')
		meta.angular = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'appId')
		meta.appId = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'timestamp')
		meta.timestamp = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'nonceStr')
		meta.nonceStr = content[i].getAttribute('content');
	if(content[i].getAttribute('name') == 'signature')
		meta.signature = content[i].getAttribute('content');
}

function isBoss($ionicLoading, $state, myPopup, data, callback){
	$ionicLoading.hide();
	if(data.isbind == 0){
		var alertPopup = myPopup.alert({
			type: 'Error',
			title: '出错啦!',
			content: '您还没有创建商户或者没有绑定商户!'
		});
		alertPopup.then(function(res){
			$state.go('createShop');
		});
	}else{
		if(data.role != 'boss'){
			var alertPopup = myPopup.alert({
				type: 'Error',
				title: '出错啦!',
				content: '您不是商户老板, 请不要越级操作!'
			});
			alertPopup.then(function(res){
				$state.go('shopCode');
			});
		}else{
			if(callback && typeof callback == 'function'){ callback();}
		}
	}
}
wx.config({
	debug: false,
	appId: meta.appId,
	timestamp: meta.timestamp,
	nonceStr: meta.nonceStr,
	signature: meta.signature,
	jsApiList: ['scanQRCode', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'openLocation', 'getLocation', 'closeWindow']
});
angular.module('myApp', ['ionic', 'myApp.controllers', 'myApp.services', 'myApp.directive'])
	.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider){
		$ionicConfigProvider.platform.ios.tabs.style('standard');
		$ionicConfigProvider.platform.ios.tabs.position('bottom');
		$ionicConfigProvider.platform.android.tabs.style('standard');
		$ionicConfigProvider.platform.android.tabs.position('bottom');
		$ionicConfigProvider.platform.ios.navBar.alignTitle('center');
		$ionicConfigProvider.platform.android.navBar.alignTitle('center');
		$ionicConfigProvider.platform.ios.views.transition('ios');
		$ionicConfigProvider.platform.android.views.transition('ios');
		$stateProvider
			.state('shopCode', {
				url: '/shopCode',
				cache: false,
				templateUrl: templatePath + 'shopCode.html',
				controller: 'shopCodeCtrl'
			})
			.state('createShop', {
				url: '/createShop',
				cache: false,
				templateUrl: templatePath + 'createShop.html',
				controller: 'createShopCtrl'
			})
			.state('bindPerson', {
				url: '/bindPerson',
				cache: false,
				templateUrl: templatePath + 'bindPerson.html',
				controller: 'bindPersonCtrl'
			})
			.state('orderList', {
				url: '/orderList',
				cache: false,
				templateUrl: templatePath + 'orderList.html',
				controller: 'orderListCtrl'
			})
			.state('actionLog', {
				url: '/actionLog',
				cache: false,
				templateUrl: templatePath + 'actionLog.html',
				controller: 'actionLogCtrl'
			})
			.state('personManage', {
				url: '/presonnel',
				cache: false,
				templateUrl: templatePath + 'presonnel.html',
				controller: 'presonnelCtrl'
			})
			.state('shopInfo', {
				url: '/shopInfo',
				cache: false,
				templateUrl: templatePath + 'shopInfo.html',
				controller: 'shopInfoCtrl'
			})
			.state('cashRecord', {
				url: '/cashRecord',
				cache: false,
				templateUrl: templatePath + 'cashRecord.html',
				controller: 'cashRecordCtrl'
			})
			.state('bindBank', {
				url: '/bindBank',
				cache: false,
				templateUrl: templatePath + 'bindBank.html',
				controller: 'bindBankCtrl'
			})
			.state('withdraw', {
				url: '/withdraw',
				cache: false,
				templateUrl: templatePath + 'withdraw.html',
				controller: 'withdrawCtrl',
			});
		$urlRouterProvider.otherwise('/shopCode');
	});
angular.module('myApp.services', [])
	.factory('myService', function($http){
		var ajax = function(a, b){
			var param = arguments[0]?arguments[0]:{},
				type = arguments[1]?arguments[1]:'post';
			switch(type){
				case 'post':
					return $http.post(meta.angular, angular.extend({ac: 'angular'}, param));
				default:
					return $http.get(meta.angular, angular.extend({ac: 'angular'}, param));
			}
		}
		return {
			getCategory: function(){
				"use strict";
				return ajax({op: 'getCategory'});
			},
			district: function(){
				return $http.get('/Public/district.json');
			},
			getSession: function(refresh){
				"use strict";
				return ajax({op: 'getSession', refresh: refresh});
			},
			createShop: function(data){
				"use strict";
				return ajax(angular.extend({op: 'createShop'}, data));
			},
			qrcode2ShopInfo: function(qrcode){
				"通过二维码获得店铺信息";
				return ajax(angular.extend({op: 'qrcode2ShopInfo', qrcode: qrcode}));
			},
			sendSms: function(mobile, action){
				"发送短信验证码";
				return ajax({op: 'sendSms', mobile: mobile, action: action});
			},
			bindPerson: function(data){
				"收银员绑定商铺";
				return ajax(angular.extend({op: 'bindPerson'}, data));
			},
			getShopInfo: function(){
				"获得当前用户所绑定商铺的详细信息";
				return ajax({op: 'getShopInfo'});
			},
			setShopInfo: function(data){
				return ajax(angular.extend({op: 'setShopInfo'}, data));
			},
			getShopOrder: function(){
				"use strict";
				return ajax({op: 'getShopOrder'});
			},
			getPresonList: function(){
				return ajax({op: 'getPresonList'});
			},
			removePreson: function(uid){
				return ajax({op: 'removePreson', uid: uid});
			},
			getCashList: function(){
				return ajax({op: 'getCashList'});
			},
			getLog: function(){
				return ajax({op: 'getLog'});
			},
			getBankData: function(){
				return ajax({op: 'getBankData'});
			},
			getAreaData: function(did){
				return ajax({op: 'getAreaData', did: did});
			},
			bindBank: function(data){
				return ajax(angular.extend({op: 'bindBank'}, data));
			},
			withdraw: function(data){
				return ajax(angular.extend({op: 'withdraw'}, data));
			}
		};
	})
	.factory('myPopup', function($ionicPopup){
		"弹出框服务";
		return {
			alert: function(param){
				"alert（警告） 对话框";
				switch(param.type){
					case 'success':
						var title = (typeof param.title == 'null')?'操作成功啦!':param.title;
						var icon = 'ion-checkmark-round';
						break;
					case 'error':
						var title = (typeof param.title == 'null')?'操作失败啦!':param.title;
						var icon = 'ion-close-round';
						break;
					default:
						var title = (typeof param.title == 'null')?'系统操作提示!':param.title;
						var icon = 'ion-information-circled';
						break;
				}
				return $ionicPopup.alert({
					title: title,
					template: '<div class="row"><div class="col col-25"><i class="icon '+icon+'"></i></div><div class="col col-75">'+param.content+'</div></div>'
				});
			}
		}
	});
angular.module('myApp.directive', [])
	.directive('uploadWidget', function(){
		"上传指令";
		return {
			restrict: 'A',
			replace: true,
			template: '<input type="image" />',
			link: function(scope, elements, attrs){
				switch(attrs.uploadWidget){
					case 'Logo':
						if(attrs.forSrc == 'notImg')
							elements.attr('src', 'http://placehold.it/90x90');
						else
							elements.attr('src', 'http://s.mywoka.com'+attrs.forSrc);
						elements.addClass('logo-img');
						break;
					case 'Banner':
						if(attrs.forSrc == 'notImg')
							elements.attr('src', 'http://placehold.it/200x90');
						else
							elements.attr('src', 'http://s.mywoka.com'+attrs.forSrc);
						elements.addClass('banner-img');
						break;
				}
				elements.bind('click', function(){
					wx.ready(function(){
						wx.chooseImage({
							count: 1, // 默认9
							sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
							sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
							success: function (res) {
								var localIds = res.localIds;
								elements.attr('src', localIds);
								wx.uploadImage({
									localId: localIds.toString(),
									isShowProgressTips: 1,
									success: function (resu) {
										var serverId = resu.serverId;
										switch(attrs.uploadWidget){
											case 'Logo':
												scope.shop.logo = serverId;
												break;
											case 'Banner':
												scope.shop.banner = serverId;
												break;
										}
									}
								});
							}
						});
					});
				});
			}
		}
	})
	.directive('buttonWidget', function(myService, $ionicLoading, myPopup){
		"按钮指令";
		return {
			restrict: 'A',
			scope: {
				forms: '='
			},
			link: function(scope, element, attrs){
				switch(attrs.buttonWidget){
					case 'sms':
						"发送短信验证码按钮";
						function sendSmsTimer(){
							"use strict";
							if (wait == 0) {
								element.removeAttr('disabled').text("重新发送短信验证码");
								wait = 60;
							} else {
								element.attr('disabled', 'disabled').text("(" + wait + "秒后)重新发送验证码");
								wait--;
								setTimeout(function(){sendSmsTimer()}, 1000)
							}
						}
						element.bind('click', function(){
							$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
							myService.sendSms(attrs.mobile, attrs.ac).success(function(resp){
								$ionicLoading.hide();
								scope.forms.sms_order_id = resp.data.order_id;
								scope.forms.sms_order_date = resp.data.order_date;
								myPopup.alert(resp);
							});
							sendSmsTimer();
						});
						break;
					case 'removePreson':
						if(attrs.forRole == 'boss'){
							element.attr('disabled', 'disabled');
						}else{
							element.bind('click', function(){
								myService.removePreson(attrs.forUid).success(function(resp){
									myPopup.alert(resp);
								});
							});
						}
						break;
				}
			}
		}
	})
	.directive('itemWidget', function(){
		return {
			restrict: 'A',
			scope: {
				dates : '@forDate',
				money: '@forMoney',
				fees: '@forFees',
				strike: '@forStrike'
			},
			template: '<p><strong>{{dates}}</strong></p>'+
			          '<span class="badge badge-balanced">已结算</span>'+
			          '<div class="item-note row"><div class="col">提现金额: </div><div class="col">￥{{money}}</div>'+
			          '<div class="col">交易佣金: </div><div class="col">￥{{fees}}</div></div>',
			link: function(iScope, iElement, iAttr){
				if(iScope.strike == 0){
					iElement.find('span').removeClass('badge-balanced').addClass('badge-assertive').text('未结算');
				}
			}
		}
	})
	.directive('isCode', function($http,$timeout,$window){
		"自定义验证是否是短信验证码";
		return {
			restrict:"A",
			require: 'ngModel',
			link: function(scope, ele, attrs, ngModelController){
				scope.$watch(attrs.ngModel, function(value) {
					if (!value) return;
					$timeout.cancel($window.timer);
					$window.timer = $timeout(function(){
						$http({
							method: 'post',
							url: meta.angular,
							data:{ac: 'validation', op: attrs.isCode, mbcode: value, mobile: attrs.mobile}
						}).success(function(data) {
							ngModelController.$setValidity('unique', data.isUnique); //这个取决于你返回的，其实就是返回一个是否正确的字段，具体的这块可以自己修改根据自己的项目
						}).error(function(data) {
							ngModelController.$setValidity('unique', false);
						});
					}, 2000);
				});
			}
		};
	});
angular.module('myApp.controllers', [])
	.controller('shopCodeCtrl', function($scope, myService, $state, myPopup){
		"店铺二维码页面控制器";
		myService.getSession(true).success(function(resp){
			if(resp.errcode == '0'){
				if(resp.isbind == 0){
					var alertPopup = myPopup.alert({
						type: 'Error',
						title: '出错啦!',
						content: '您还没有创建商铺或者没有绑定商铺!'
					});
					alertPopup.then(function(res){
						$state.go('createShop');
					});
				}else{
					$scope.shopTitle = resp.title;
					$scope.qrcodeUrl = resp.qrcodeUrl;
				}
			}else{
				myPopup.alert(resp);
			}
		});
	})
	.controller('createShopCtrl', function($scope, $ionicLoading, myService, $state, myPopup){
		"创建店铺页面控制器";
		$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
		$scope.formData = {
			sms_order_id: 'S',
			sms_order_date: '',

		};
		myService.getSession().success(function(resp){
			$ionicLoading.hide();
			if(resp.isbind && resp.isbind != 0){
				var alertPopup = myPopup.alert({
					type: 'Error',
					title: '出错啦!',
					content: '您已经创建过商铺或者绑定过商铺!请不要重复操作!'
				});
				alertPopup.then(function(res){
					$state.go('shopCode');
				});
			}else{
				wx.ready(function(){
					wx.getLocation({
						type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
						success: function(res){
							myService.getCategory().success(function(cate){
								"获得店铺分类数据";
								$scope.category = cate.data;
							});
							$scope.formData = {
								latitude: res.latitude,     // 纬度，浮点数，范围为90 ~ -90
								longitude: res.longitude,   // 经度，浮点数，范围为180 ~ -180。
								accuracy: res.accuracy,     // 位置精度
							};
						}
					});
					$scope.submit = function(){
						$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
						myService.createShop($scope.formData).success(function(resp){
							"创建店铺表单提交";
							$ionicLoading.hide();
							var alertPopup = myPopup.alert({
								type: resp.type,
								title: resp.title,
								content: resp.content
							});
							if(resp.errcode == '0'){
								alertPopup.then(function(){$state.go('bindBank');});
							}
						});
					};
				});
			}
		});
	})
	.controller('bindPersonCtrl', function($scope, myService, $state, $ionicLoading, myPopup){
		"收银员绑定店铺控制器";
		myService.getSession().success(function(resp){
			if(resp.isbind && resp.isbind != 0){
				var alertPopup = myPopup.alert({
					type: 'Error',
					title: '出错啦!',
					content: '您已经创建过商铺或者绑定过商铺!请不要重复操作!'
				});
				alertPopup.then(function(){$state.go('shopCode');});
			}else{
				wx.config({
					debug: false,
					appId: meta.appId,
					timestamp: meta.timestamp,
					nonceStr: meta.nonceStr,
					signature: meta.signature,
					jsApiList: ['scanQRCode']
				});
				wx.ready(function(){
					$scope.scanQrCode = function(){
						wx.scanQRCode({
							needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
							scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码，默认二者都有
							success: function(res){
								$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
								myService.qrcode2ShopInfo(res.resultStr).success(function(resp){
									$ionicLoading.hide();
									$scope.formData = {
										title: resp.data.title,
										suite: resp.data.suite,
										boss_mobile: resp.data.mobile,
										sid: resp.data.sid,
									};
									$scope.submit = function(){
										$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
										myService.bindPerson($scope.formData).success(function(resp){
											"收银员绑定店铺表单提交";
											$ionicLoading.hide();
											var alertPopup = myPopup.alert(resp);
											if(resp.errcode == '0'){
												alertPopup.then(function(){$state.go('shopCode');});
											}
										});
									}
								});
							}
						});
					}
				});
			}
		});
	})
	.controller('orderListCtrl', function($scope, myService, $state, myPopup){
		"订单列表控制器";
		myService.getSession().success(function(resp){
			if(resp.isbind == 0){
				var alertPopup = myPopup.alert({
					type: 'Error',
					title: '出错啦!',
					content: '您还没有创建商户或者没有绑定商户!'
				});
				alertPopup.then(function(res){
					$state.go('createShop');
				});
			}else{
				myService.getCashList().success(function(resp){
					if(resp.errcode != '0'){
						var alertPopup = myPopup.alert(resp);
						alertPopup.then(function(res){
							$state.go('createShop');
						});
					}else{
						$scope.orderList = resp.data;
					}
				});
			}
		});
	})
	.controller('actionLogCtrl', function($scope, $state, myService, myPopup){
		myService.getLog().success(function(resp){
			if(resp.errcode != '0'){
				var alertPopup = myPopup.alert(resp);
				alertPopup.then(function(res){
					$state.go('createShop');
				});
			}else{
				$scope.logList = resp.data;
			}
		});
	})
	.controller('presonnelCtrl', function($scope, $state, myService, myPopup){
		"员工列表控制器";
		myService.getSession().success(function(resp){
			if(resp.isbind == 0){
				var alertPopup = myPopup.alert({
					type: 'Error',
					title: '出错啦!',
					content: '您还没有创建商户或者没有绑定商户!'
				});
				alertPopup.then(function(res){
					$state.go('createShop');
				});
			}else if(resp.role != 'boss'){
				var alertPopup = myPopup.alert({
					type: 'Error',
					title: '出错啦!',
					content: '您不是商户老板, 请不要越级操作!'
				});
				alertPopup.then(function(res){
					$state.go('shopCode');
				});
			}else{
				myService.getPresonList().success(function(resp){
					if(resp.type == 'Error'){
						var alertPopup = myPopup.alert(resp);
						alertPopup.then(function(res){
							$state.go('createShop');
						});
					}else{
						$scope.presonList = resp.data;
					}
				});
			}
		});
	})
	.controller('shopInfoCtrl', function($scope, $state, myService, myPopup){
		"设置店铺基础资料控制器";
		/*$scope.shop = {
			logo: 'http://placehold.it/90x90',
			banner: 'http://placehold.it/200x90',
		}*/
		myService.getSession().success(function(resp){
			if(resp.isbind == 0){
				var alertPopup = myPopup.alert({
					type: 'Error',
					title: '出错啦!',
					content: '您还没有创建商户或者没有绑定商户!'
				});
				alertPopup.then(function(res){
					$state.go('createShop');
				});
			}else if(resp.role != 'boss'){
				var alertPopup = myPopup.alert({
					type: 'Error',
					title: '出错啦!',
					content: '您不是商户老板, 请不要越级操作!'
				});
				alertPopup.then(function(res){
					$state.go('shopCode');
				});
			}else{
				myService.getCategory().success(function(cate){
					"获得店铺分类数据";
					$scope.category = cate.data;
				});
				$scope.shop = resp;
				$scope.submit = function(){
					myService.setShopInfo($scope.shop).success(function(resp){
						myPopup.alert({
							type: 'success',
							title: resp.title,
							content: resp.content
						});
					})
				};
			}
		});
	})
	.controller('cashRecordCtrl', function($scope, $state, myService, myPopup){
		myService.getCashList().success(function(resp){
			if(resp.type == 'Error'){
				var alertPopup = myPopup.alert(resp);
				alertPopup.then(function(res){
					$state.go('createShop');
				});
			}else{
				$scope.cashList = resp.data;
			}
		});
	})
	.controller('bindBankCtrl', function($scope, $ionicLoading, myService, $state, myPopup){
		$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
		myService.getBankData().success(function(resp){
			isBoss($ionicLoading, $state, myPopup, resp.data, function(){
				if(resp.data.is_bind_bank == '0'){
					$scope.formData = {
						user_name: resp.data.user_name,
						cert_id: resp.data.cert_id,
					}
					$scope.prov = resp.data.prov;
					$scope.bank = resp.data.bank;
					$scope.area = function(){
						$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
						myService.getAreaData($scope.formData.card_prov.id).success(function(rep){
							$ionicLoading.hide();
							$scope.area = rep.data;
						});
					}
					$scope.submit = function(){
						$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
						myService.bindBank($scope.formData).success(function(res){
							$ionicLoading.hide();
							var alertPopup = myPopup.alert(resp);
							if(resp.errcode == '0'){
								alertPopup.then(function(res){
									$state.go('shopCode');
								});
							}
						})
					}
				}else{
					var alertPopup = myPopup.alert({
						type: 'Error',
						title: '出错啦!',
						content: '您已经完成提现银行卡的绑定操作, 请不要重复操作!'
					});
					alertPopup.then(function(){$state.go('shopCode');});
				}
			});
		});
	})
	.controller('withdrawCtrl', function($scope, $ionicLoading, myService, $state, myPopup){
		$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
		myService.getBankData().success(function(resp){
			isBoss($ionicLoading, $state, myPopup, resp.data, function(){
				if(resp.data.is_bind_bank == '1'){
					$scope.formData = resp.data;
					$scope.submit = function(){
						$ionicLoading.show({content: 'Loading', animation: 'fade-in', showBackdrop: true, maxWidth: 200, showDelay: 0});
						delete $scope.formData.bank;
						delete $scope.formData.prov;
						myService.withdraw($scope.formData).success(function(res){
							$ionicLoading.hide();
							var alertPopup = myPopup.alert(res);
							if(resp.errcode == '0'){
								alertPopup.then(function(){$state.go('shopCode');});
							}
						});
					}
				}else{
					var alertPopup = myPopup.alert({
						type: 'Error',
						title: '出错啦!',
						content: '您尚未进行银行卡的绑定操作, 请进行提现银行卡绑定操作!'
					});
					alertPopup.then(function(){$state.go('bindBank');});
				}
			});
		});
	})
	.controller('NavCtrl', ['$scope', '$ionicActionSheet', '$state', function($scope, $ionicActionSheet, $state){
		$scope.goShopCode = function(){
			"use strict";
			$state.go('shopCode');
		}
		$scope.openMenu1 = function(){
			$ionicActionSheet.show({
				buttons: [
					{text: '创建商户'},
					{text: '员工绑定'},
					{text: '订单列表'},
					{text: '操作日志'}
				],
				titleText: '商户功能子菜单',
				buttonClicked: function(index){
					switch(index){
						case 0:
							$state.go('createShop');
							break;
						case 1:
							$state.go('bindPerson');
							break;
						case 2:
							$state.go('orderList');
							break;
						case 3:
							$state.go('actionLog');
					}
					return true;
				}
			});
		};
		$scope.openMenu2 = function(){
			$ionicActionSheet.show({
				buttons: [
					{text: '统计报表'},
					{text: '员工管理'},
					{text: '店铺信息管理'},
					{text: '绑定银行卡'},
					{text: '余额提现'},
				],
				titleText: '老板后台子菜单',
				buttonClicked: function(index){
					switch(index){
						case 0:
							$state.go('cashRecord');
							break;
						case 1:
							$state.go('personManage');
							break;
						case 2:
							$state.go('shopInfo');
							break;
						case 3:
							$state.go('bindBank');
							break;
						case 4:
							$state.go('withdraw');
					}
					return true;
				}
			});
		};
	}
]);